package top.xia17.plugins.fast.user.ds;

import cn.hutool.core.util.StrUtil;
import top.xia17.plugins.fast.common.database.dynamic.DsSwitch;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import top.xia17.plugins.fast.user.config.UserProperties;

/**
 * 用户使用的数据源切换Aop切面
 * 此方式已被废弃，将在未来删除
 * @author xia17
 */
@Aspect
@RequiredArgsConstructor
@Slf4j
@Deprecated
public class UserDsAspect {

    private final DsSwitch dsSwitch;
    private final UserProperties userProperties;

    private final static String DEFAULT_DATASOURCE_NAME = "master";


    @Pointcut("execution( * top.xia17.plugins.fast.common.database.jpa.extension.JpaServiceImpl+.*(..)) && @target(top.xia17.plugins.fast.user.ds.UserDDS)")
    public void point() {
    }

    @Before("point()")
    public void before(JoinPoint joinPoint) {
        // 是master数据源不切换
        if (DEFAULT_DATASOURCE_NAME.equals(userProperties.getDynamicDatasourceName())){
            // 且必须当前数据源是master
            if (StrUtil.isBlank(dsSwitch.peek()) || DEFAULT_DATASOURCE_NAME.equals(dsSwitch.peek())){
                return;
            }
        }
        log.error("切换数据源");
        dsSwitch.push(userProperties.getDynamicDatasourceName());
    }

    @After("point()")
    public void after(JoinPoint joinPoint) {
        log.error("移除数据源");
        dsSwitch.poll();
    }





}
